#!groovy

@Library('jenkinslib@master') _

def build = new org.devops.build()
def tools = new org.devops.tools()
def email = new org.devops.toemail()


String buildType  = "${env.buildType}"
String buildShell = "${env.buildShell}"
String branchName = "${env.branchName}"
String srcUrl     = "${env.srcUrl}"
String userEmail  = "15071567976@163.com"


pipeline {
    agent {
        node {
            label "master"
        }
    }

    stages {
        stage('CREATE PROJECT DIR') {
            steps {
                script {
                    def dirPath = "${WORKSPACE}/project"
                    new File(dirPath).mkdirs()
                }
            }
        }

        stage('GETCODE') {
            steps {
                dir('project') {
                    script {
                        println("getcode")

                        // println("${branchName}")
                        tools.PrintMes("获取代码","green")
                    
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]],
                                doGenerateSubmoduleConfigurations: false,
                                extensions: [],
                                submoduleCfg: [],
                                userRemoteConfigs: [[credentialsId: 'gitee', url: "${srcUrl}"]]
                        ])
                    }
                }
            }
        }
        
        stage("MAVEN_BUILD") {
            steps {
                script {
                    // 使用环境变量来引用 Maven 工具
                    def mavenHome = tool 'M3'
                    println("${mavenHome}") 
                    // 添加错误处理
                    try {
                        sh "${mavenHome}/bin/mvn -v"
                    } catch (Exception e) {
                        echo "Maven build failed"
                        error "Build failed due to Maven error"
                    }
                }
            }
        }
    }

    post {
        always{
            script{
                println("always")
            }
        }
        
        success{
            script{
                println("success")
                email.Email("流水线成功", userEmail)
            }
        }

        failure{
            script{
                println("failure")
            }
        }
        
        aborted{
            script{
                println("aborted")
            }
        }
    }
}